#!/usr/bin/python

import os, imp

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

print ('******************\ncompile shaders into JS source ...')
ShaderDir = '../shaders'
src = "var Shaders = {\n\n"
for f in os.listdir(ShaderDir):

    if f.find('.glsl') == -1: continue
    name = f.replace('.glsl', '')
    src += "'%s': `#version 300 es" % name
    path = os.path.join(ShaderDir, f)
    lines = open(path).read().strip().split('\n')
    code = []
    code.append('')
    code.extend(lines)

    for i, line in enumerate(code):
        src += line.lstrip('\n') + '\n'
        if i==len(code)-1:
            src += "`,\n\n"

src += "}"
open("../js/shaders.js", 'w').write(src)

print ('\n******************\nminify code into trinity.min.js ...')
# Construct the command for Google Closure Compiler, to generate minified code
jsDestPath = "../js/compiled/trinity.min.js"
jsSources = [ 
'../js/thirdparty/jquery-3.3.1.min.js',
'../js/thirdparty/jquery-ui.min.js',
'../js/thirdparty/jquery-ui.css.js',
'../js/thirdparty/codemirror/codemirror.js',
'../js/thirdparty/codemirror/panel.js',
'../js/thirdparty/codemirror/buttons.js',
'../js/thirdparty/codemirror/codemirror.css.js',
'../js/thirdparty/codemirror/clike.js',
'../js/thirdparty/gif.js/gif.js',
'../js/thirdparty/gif.js/gif.worker.js',
'../js/thirdparty/three/three.min.js',
'../js/thirdparty/three/libs/stats.min.js',
'../js/thirdparty/three/libs/dat.gui.min.js',
'../js/thirdparty/three/controls/OrbitControls.js',
'../js/gl.js',
'../js/presets.js',
'../js/gui.js',
'../js/shaders.js',
'../js/renderer.js',
'../js/solver.js',
'../js/trinity.js'
]

lib_files = ' '.join(jsSources)
cmd = '''
java -jar closure-compiler/compiler.jar --js %s  --js_output_file %s
''' % (lib_files, jsDestPath)

os.system(cmd)

print ('\n******************\nbuild documentation via jsdoc2md ...')
jsSources = [
'../js/trinity.js',
'../js/solver.js',
'../js/renderer.js',
'../js/gui.js',
'../js/gl.js'
]
api_files = ' '.join(jsSources)
cmd = '''
jsdoc2md --template ../docs/API.hbs --files %s > ../docs/API.md''' % api_files
os.system(cmd)



